package com.bea.ftd.dashboard.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bea.ftd.common.ValidationException;
import com.bea.ftd.common.dao.FallbackInfoRepo;
import com.bea.ftd.common.entity.FallbackInfo;
import com.bea.ftd.common.enums.ValidationErrorCode;
import com.bea.ftd.dashboard.service.IFallbackInfoService;
import com.bea.ftd.dashboard.service.IGatewayService;
import com.bea.ftd.dashboard.validator.BooleanValidator;
import com.bea.ftd.dashboard.validator.StringValidator;

@Service
public class FallbackInfoServiceImpl implements IFallbackInfoService, IGatewayService {
	private Logger LOGGER = LoggerFactory.getLogger(ApiDefineServiceImpl.class);

	@Autowired
	private FallbackInfoRepo fallbackInfoRepo;
	@Autowired
	private StringValidator stringValidator;
	@Autowired
	private BooleanValidator booleanValidator;

	@Override
	public List<FallbackInfo> getAllFallbackInfos() {
		try {
			return fallbackInfoRepo.findAll();
		} catch (Exception e) {
			LOGGER.error("error when querying apiDefines from database " + e.getMessage());
			return null;
		}
	}

	@Override
	public void addFallbackInfo(FallbackInfo fallbackInfo) throws ValidationException {

		validateInputParams(fallbackInfo);
		setCreateOrUpdateTime(fallbackInfo, fallbackInfoRepo);
		fallbackInfoRepo.save(fallbackInfo);

	}
	
	private void validateInputParams(FallbackInfo fallbackInfo) throws ValidationException {
		
		if (stringValidator.isEmptyString(fallbackInfo.getFallbackUrl())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "回退地址不能为空");
		}

		if (stringValidator.isEmptyString(fallbackInfo.getKafkaTopic())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "kafka Topic不能为空");
		}

		if (!booleanValidator.isBooleanType(fallbackInfo.getIsActivated())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "无效的isActivated值");
		}
	}

}
